# -*- coding: utf-8 -*-

from WSThread import WSThread
import re
import dns.message
import dns.query
import queue
import time

class DnsBruteThread(WSThread):
    def __init__(self, job, result, domain, msymbol, dns_srv, counter):
        super().__init__(job, result)
        self.domain = domain
        self.dns_srv = dns_srv
        self.counter = counter
        self.msymbol = msymbol

    def run(self):
        ipRe = re.compile(r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})")
        nsRespRe = re.compile(r";ANSWER\s(?P<data>(.|\s)*)\s;AUTHORITY", re.M)

        while self.running:
            try:
                host = self.job.get()
                self.counter.up()

                check_name = self.domain.replace(self.msymbol, host)
                query = dns.message.make_query(check_name, 'A');
                try:
                    result = dns.query.tcp(query, self.dns_srv.get(), timeout=2)
                except Exception:
                    self.result.put("error", check_name)
                    time.sleep(5)
                    continue

                response = nsRespRe.search(result.to_text())
                if response is not None:
                    for ip in ipRe.findall(response.group('data')):
                        self.result.put("exists", check_name, ip)

                self.job.task_done(host)
            except queue.Empty:
                self.running = False